package com.example.demo.security.sysMessage.dao;

import com.example.demo.db.BaseDao;
import com.example.demo.security.sysMessage.entity.MessagesBean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class MessageDao extends BaseDao<MessagesBean ,Integer> {



    public List<MessagesBean> queryFriendMessage(Integer userId, Integer id){
        String sql="SELECT g.id,g.groupId,g.userId,g.receiveId,g.message,(SELECT u.userName FROM userInfo u WHERE u.id=g.userId) userName  FROM groupMessage g WHERE g.groupId=0 ";
        List<Object> params=new ArrayList<>();
        if(userId!=null){
            sql+=" AND (g.userId=? OR g.receiveId=?)";
            params.add(userId);
            params.add(userId);
        }
        if (id!=null){
            sql+=" AND (g.receiveId=? OR g.userId=?)";
            params.add(id);
            params.add(id);
        }
        return getJtl().query(sql,new BeanPropertyRowMapper<>(MessagesBean.class),params.toArray());
    }

    public List<MessagesBean> queryGroupMessage(Integer id){
        String sql="SELECT g.id,g.groupId,g.userId,g.receiveId,g.message,(SELECT u.userName FROM userInfo u WHERE u.id=g.userId) userName  FROM groupMessage g WHERE g.groupId=?";
        return getJtl().query(sql,new BeanPropertyRowMapper<>(MessagesBean.class),id);
    }

    public Integer insertMessage(MessagesBean messagesBean){
        String sql="INSERT INTO groupMessage(groupId,userId,receiveId,message) VALUES(:groupId, :userId, :receiveId, :message)";
        return getNamedJtl().update(sql,new BeanPropertySqlParameterSource(messagesBean));
    }
}
